package com.yujie.utils;

import com.yujie.model.SysUser;
import com.yujie.model.dto.SysUserDTO;
import com.yujie.security.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class UserUtil {
    public static SysUserDTO getUser(){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            Object principal = auth.getPrincipal();
            if (principal != null && principal instanceof UserDetails) {
                SysUserDTO user = ((LoginUser) principal).getSysUser();
                if (user != null) {
                    return user;
                }
            }
        }
        return null;
    }

    /**
     * 判断用户是否拥有角色
     * @param roleName 可访问菜单角色名称
     * @return
     */
    public Boolean hasRole(String roleName){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
        List<String> roleList = new ArrayList<>();
        for (GrantedAuthority authority : authorities) {
            roleList.add(authority.getAuthority());
        }
        return roleList.contains(roleName);
    }
}
